require('dotenv').config(); // 放在文件的最顶部，确保环境变量被加载

const Koa = require('koa');
const serve = require('koa-static');
const bodyParser = require('koa-bodyparser');
const { koaBody } = require('koa-body');
const path = require('path');
const mount = require('koa-mount');
const bcrypt = require('bcryptjs');// 引入bcryptjs模块

const Router = require('@koa/router');
const userRouter = require('./routes/user')
const sightRouter = require('./routes/sight')
const articleRouter = require('./routes/article')
const uploadRouter = require('./routes/upload')

const commentRouter = require('./routes/comment')
const ticketRouter = require('./routes/ticket')
const orderRouter = require('./routes/order')
const router = new Router();
const { sequelize, DataTypes } = require('./databases/index');

const cors = require('@koa/cors');

(async () => {
  try {
    // 禁用alter选项以避免自动删除外键
    await sequelize.sync({ force: false, alter: false }); // 同步所有模型到数据库，关闭alter以避免索引重复问题
    console.log("All models were synchronized successfully.");

    const app = new Koa();
    // 配置koa-body中间件来处理文件上传
    app.use(koaBody({
      multipart: true, // 支持文件上传
      formidable: {
        uploadDir: path.join(__dirname, 'static/img'), // 设置文件上传目录
        keepExtensions: true, // 保持文件的后缀
        maxFieldsSize: 2 * 1024 * 1024, // 文件上传大小限制
      }
    }));

    app.use(bodyParser());

    //托管静态资源文件夹
    app.use(mount('/ss', serve(path.join(__dirname, 'static'))));

    //koa跨域配置
    app.use(cors({
      origin(ctx) {
        return '*';
      }
    }))

    // Use router middleware
    router.use(userRouter.routes())
    router.use(sightRouter.routes())
    router.use(articleRouter.routes())
    router.use(uploadRouter.routes())

    router.use(commentRouter.routes())
    router.use(ticketRouter.routes())
    router.use(orderRouter.routes())
    app.use(router.routes());
    app.use(router.allowedMethods());
    app.use(cors());

    app.listen(3000)
console.log('listening on port 3000');
  } catch (error) {
    console.error('Failed to start server:', error);
    process.exit(1);
  }
})();